/*
 * @Author: your name
 * @Date: 2022-03-19 22:10:49
 * @LastEditTime: 2022-03-19 22:23:53
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \driving\src\auth\role.guard.ts
 */

import { CanActivate, ExecutionContext, Injectable, SetMetadata } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { JwtService } from "@nestjs/jwt";


@Injectable()
export class RolesGuard implements CanActivate{
  constructor(
    private readonly reflector:Reflector,
    private readonly jwtService:JwtService,
  ){}
  canActivate(context:ExecutionContext):boolean{
    // 获取路由角色
    const roles = this.reflector.get('roles',context.getHandler());
    if(!roles){
      return true;
    }
    // 读取user
    const req = context.switchToHttp().getRequest();
    const user = req.user;
    if(!user){
      return false;
    }
    const hasRoles = roles.some((role) => role === user.role);
    return hasRoles
  }
}
// 定义一个角色装饰器@Roles
export const Roles = (...roles:string[]) => SetMetadata('roles',roles);